package vashion.azeroth.core.service.tran.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import vashion.azeroth.common.math.BigDecimalUtil;
import vashion.azeroth.contant.AzerothConstants;
import vashion.azeroth.core.item.pojo.ItemDO;
import vashion.azeroth.core.item.pojo.ItemSkuDO;
import vashion.azeroth.core.manager.item.BaseItemSkuManager;
import vashion.azeroth.core.manager.item.ItemReadManger;
import vashion.azeroth.core.manager.personal.ConfigVipManager;
import vashion.azeroth.core.manager.personal.PersonalMemberManager;
import vashion.azeroth.core.manager.personal.PersonalPublishFilesManager;
import vashion.azeroth.core.manager.personal.tran.PersonalRebateInfoManager;
import vashion.azeroth.core.manager.personal.tran.PersonalSnapshotManager;
import vashion.azeroth.core.personal.pojo.ConfigVip;
import vashion.azeroth.core.personal.pojo.PersonalMember;
import vashion.azeroth.core.personal.pojo.PersonalPublishFiles;
import vashion.azeroth.core.personal.tran.pojo.PersonalDisburse;
import vashion.azeroth.core.personal.tran.pojo.PersonalRebateInfo;
import vashion.azeroth.core.personal.tran.pojo.PersonalSnapshot;
import vashion.azeroth.core.personal.tran.pojo.PersonalSnapshotExt;
import vashion.azeroth.core.personal.tran.pojo.PersonalSnapshotSku;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.service.base.BaseService;
import vashion.azeroth.core.service.tran.PersonalSnapshotService;

@Service
public class PersonalSnapshotServiceImpl extends BaseService implements PersonalSnapshotService {

	private final static Logger log = LoggerFactory.getLogger(PersonalSnapshotServiceImpl.class);
	
	@Autowired
	private PersonalSnapshotManager snapshotManager;
	@Autowired
	private BaseItemSkuManager baseItemSkuManager;
	@Autowired
	private ItemReadManger itemReadManger;
	@Autowired
	private ConfigVipManager configVipManager;
	@Autowired
	private PersonalRebateInfoManager rebateInfoManager;
	@Autowired
	private PersonalPublishFilesManager publishFilesManager;
	@Autowired
	private PersonalMemberManager memberManager;
	
	@Value("#{settings['address']}")
	private String address;
	@Value("#{settings['zipcode']}")
	private String zipcode;
	@Value("#{settings['name']}")
	private String name;
	@Value("#{settings['phone']}")
	private String phone;
	
	@Override
	public ApiResult<List<PersonalSnapshotExt>> queryReturnGoodsOrder(PersonalSnapshot snapshot) {
		
		ApiResult<List<PersonalSnapshotExt>> result = new ApiResult<List<PersonalSnapshotExt>>();
		
		int count = snapshotManager.queryReturnGoodsOrderCnt(snapshot);
		
		initPages(snapshot, count);
		
		List<PersonalSnapshotExt> snapshots = snapshotManager.queryReturnGoodsOrder(snapshot);
		
		for (PersonalSnapshotExt snapshotExt : snapshots) {
			snapshotExt.setAddress(address);
			snapshotExt.setZipcode(zipcode);
			snapshotExt.setName(name);
			snapshotExt.setPhone(phone);
		}
		
		result.setData(snapshots);
		
		return ApiResult.newSuccessResult(snapshots);
	}
	
	@Override
	public ApiResult<PersonalSnapshot> queryReturnGoodInfo(PersonalSnapshot snapshot) {
		
		ApiResult<PersonalSnapshot> result = new ApiResult<PersonalSnapshot>();
		
		PersonalSnapshot dbsnapshot = snapshotManager.getSnapshot(snapshot);
		
		//获取类目关税
		ApiResult<ItemDO> retult = itemReadManger.getItemDetail(dbsnapshot.getItemId(), Boolean.FALSE);
		ItemDO item = retult.getData();
		
		Long returnPrice = calTariff(item, dbsnapshot.getPrice());
		
		dbsnapshot.setReturnPrice(returnPrice);
		
		result.setData(dbsnapshot);
		
		return ApiResult.newSuccessResult(dbsnapshot);
	}
	
	public List<PersonalSnapshot> queryEnableRebateOrder() {
		return snapshotManager.queryEnableRebateOrder();
	}
	
	@Override
	public void executeRebate() {
		List<PersonalSnapshot> snapshots = snapshotManager.queryEnableRebateOrder();
		
		List<ConfigVip> configVips = configVipManager.findAll(new ConfigVip());
		Map<String, BigDecimal> configVipMaps = new HashMap<String, BigDecimal>();
		
		for (ConfigVip configVip : configVips) {
			configVipMaps.put(configVip.getVipLevel(), configVip.getRebateRate());
		}
		
		for (PersonalSnapshot snapshot : snapshots) {
			try {
				//获取类目返佣返现比例
				ApiResult<ItemDO> retult = itemReadManger.getItemDetail(snapshot.getItemId(), Boolean.FALSE);
				ItemDO item = retult.getData();
				
				PersonalMember buyerMember = memberManager.get(snapshot.getMemberId());
				//返佣金给发贴者与购买者
				if(null != snapshot.getPublishFileId()) {
					long commission = item.getCommission();
					PersonalPublishFiles publishFile = publishFilesManager.get(snapshot.getPublishFileId());
					PersonalMember publishMember = memberManager.get(publishFile.getMemberId());
					
					//发贴人是购买者人上线,发贴人返佣70%,购买人返佣30%
					if(buyerMember.getInviteMemberId() == publishFile.getMemberId()) {
						PersonalRebateInfo rebateInfo = new PersonalRebateInfo();
						rebateInfo.setDisburseNo(snapshot.getDisburseNo());
						rebateInfo.setItemId(snapshot.getItemId());
						rebateInfo.setRebateAmount(BigDecimalUtil.multiply(new BigDecimal(commission), new BigDecimal(0.7)).longValue() * snapshot.getQuantity());
						//返佣给发贴人
						rebateInfo.setMemberId(publishMember.getMemberId());
						rebateInfo.setMemberName(publishMember.getMemberName());
						//购买人
						rebateInfo.setBuyMemberId(buyerMember.getMemberId());
						rebateInfo.setBuyMemberName(buyerMember.getMemberName());
						//发贴人
						rebateInfo.setPublishMemberId(publishMember.getMemberId());
						rebateInfo.setPublishMemberName(publishMember.getMemberName());
						rebateInfo.setStatus(AzerothConstants.PersonalRebateInfo.RebateInfoStatus.created);
						rebateInfo.setType(AzerothConstants.PersonalRebateInfo.RebateInfoType.rebate);
						rebateInfo.setTimeAdd(new Date());
						rebateInfoManager.save(rebateInfo);
						
						//返佣给购买人
						rebateInfo.setMemberId(buyerMember.getMemberId());
						rebateInfo.setMemberName(buyerMember.getMemberName());
						rebateInfo.setRebateAmount(BigDecimalUtil.multiply(new BigDecimal(commission), new BigDecimal(0.3)).longValue() * snapshot.getQuantity());
						rebateInfoManager.save(rebateInfo);
					} else {
						PersonalRebateInfo rebateInfo = new PersonalRebateInfo();
						rebateInfo.setDisburseNo(snapshot.getDisburseNo());
						rebateInfo.setItemId(snapshot.getItemId());
						rebateInfo.setRebateAmount(commission * snapshot.getQuantity());
						//返佣给发贴人
						rebateInfo.setMemberId(publishMember.getMemberId());
						rebateInfo.setMemberName(publishMember.getMemberName());
						//购买人
						rebateInfo.setBuyMemberId(buyerMember.getMemberId());
						rebateInfo.setBuyMemberName(buyerMember.getMemberName());
						//发贴人
						rebateInfo.setPublishMemberId(publishMember.getMemberId());
						rebateInfo.setPublishMemberName(publishMember.getMemberName());
						rebateInfo.setStatus(AzerothConstants.PersonalRebateInfo.RebateInfoStatus.created);
						rebateInfo.setType(AzerothConstants.PersonalRebateInfo.RebateInfoType.rebate);
						rebateInfo.setTimeAdd(new Date());
						rebateInfoManager.save(rebateInfo);
					}
				}
				
				//返现给购买者
				if(null != snapshot.getVipLevel()) {
					//VIP级别对应的返现比例
					BigDecimal rebateRate = configVipMaps.get(snapshot.getVipLevel());
					long baseRebateAmount = item.getCashBack();
					
					PersonalRebateInfo rebateInfo = new PersonalRebateInfo();
					rebateInfo.setDisburseNo(snapshot.getDisburseNo());
					rebateInfo.setItemId(snapshot.getItemId());
					rebateInfo.setRebateAmount(BigDecimalUtil.multiply(new BigDecimal(baseRebateAmount), rebateRate).longValue() * snapshot.getQuantity());
					rebateInfo.setFormula(String.valueOf(baseRebateAmount) + "*" + String.valueOf(rebateRate) + "*" + String.valueOf(snapshot.getQuantity()));
					rebateInfo.setMemberId(buyerMember.getMemberId());
					rebateInfo.setMemberName(buyerMember.getMemberName());
					rebateInfo.setBuyMemberId(buyerMember.getMemberId());
					rebateInfo.setBuyMemberName(buyerMember.getMemberName());
					rebateInfo.setStatus(AzerothConstants.PersonalRebateInfo.RebateInfoStatus.created);
					rebateInfo.setType(AzerothConstants.PersonalRebateInfo.RebateInfoType.rebate);
					rebateInfo.setTimeAdd(new Date());
					
					rebateInfoManager.save(rebateInfo);
				}
			} catch (Exception e) {
				log.error("返现异常,订单号=" + snapshot.getDisburseNo() + " 商品ID=" + snapshot.getItemId());
			}
	
		}
	}
	
	/**
	 * 计算关税
	 * @return
	 */
	public long calTariff(ItemDO item,  long price) {
		Long returnPrice = price;
		BigDecimal tariff = item.getTariff();
		if(null != tariff) {
			returnPrice = price - BigDecimalUtil.multiply(new BigDecimal(price), tariff).longValue();
		}
		return returnPrice;
	}
	
	/**
	 * 获取用户下单时服务器端商品信息
	 */
	public List<PersonalSnapshot> fillingSnapshot(List<PersonalSnapshot> snapshots) {
		List<Long> skuIds = new ArrayList<Long>();
		for (PersonalSnapshot snapshot : snapshots) {
			skuIds.add(snapshot.getSkuId());
		}
		if(skuIds.isEmpty()) {
			return snapshots;
		}
		
		Map<Long, ItemSkuDO> skuMap = baseItemSkuManager.getSkuDetail(skuIds);
		for (PersonalSnapshot snapshot : snapshots) {
			ItemSkuDO skuDO = skuMap.get(snapshot.getSkuId());
			snapshot.setItemId(skuDO.getItemId());
			snapshot.setPic(null == skuDO.getPic()?"":skuDO.getPic());
			snapshot.setPrice(skuDO.getItemPrice());
			snapshot.setTitle(skuDO.getItemTitle());
			snapshot.setSkuName(skuDO.getSkuName());
			snapshot.setSupplierMemberId(skuDO.getUserId());
		}
		//主动垃圾回收
		skuIds = null;
		
		return snapshots;
	}
	
	public void fillingSnapshot(PersonalDisburse disburse) {
		
        List<Long> skuIds = new ArrayList<Long>();
		for (PersonalSnapshotSku sku : disburse.getSkus()) {
			skuIds.add(sku.getId());
		}
		
		Map<Long, ItemSkuDO> skuMap = baseItemSkuManager.getSkuDetail(skuIds);
		ItemSkuDO itemSkuDO = skuMap.get(skuIds.get(0));
		disburse.getSnapshot().setItemSkuDO(itemSkuDO);
		
		disburse.getSnapshot().setSupplierMemberId(itemSkuDO.getUserId());
			
		//主动垃圾回收
		skuIds = null;
	}
	
}
